package transforms

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/edgexfoundry/app-functions-sdk-go/v2/pkg/util"

	"github.com/edgexfoundry/app-functions-sdk-go/v2/pkg/interfaces"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/dtos"
)

// Conversion Struct
type Conversion struct {
}

// NewConversion returns a conversion struct
func NewConversion() Conversion {
	return Conversion{}
}

func (f Conversion) PrintToConsole(ctx interfaces.AppFunctionContext, data interface{}) (bool, interface{}) {
	ctx.LoggingClient().Debug("PrintToConsole")

	if data == nil {
		return false, errors.New("PrintToConsole: No data received")
	}

	// Data is expected to be a JSON response to previous command executed.
	bytes, err := util.CoerceType(data)
	if err != nil {
		return false, fmt.Errorf("PrintToConsole: CoerceType failed: %s", err.Error())
	}

	strData := string(bytes)
	ctx.LoggingClient().Info(strData)

	return true, data
}

// TransformToCloudFormat converts the event into AWS readable format
func (f Conversion) TransformToCloudFormat(ctx interfaces.AppFunctionContext, data interface{}) (continuePipeline bool, stringType interface{}) {
	if data == nil {
		return false, errors.New("no Event received")
	}

	ctx.LoggingClient().Debug("Transforming to iotkit format")

	event, ok := data.(dtos.Event)
	if !ok {
		return false, errors.New("unexpected type received")
	}

	readings := map[string]interface{}{}

	//{"id":"2a72ddb8-7a84-4a57-b745-97698716fb9e","params":{"volt":26}}
	readings["id"] = event.Id
	params := map[string]interface{}{}
	for _, reading := range event.Readings {
		name := reading.ResourceName
		value := reading.Value

		params[name] = value
	}
	readings["params"] = params
	readings["deviceName"] = event.DeviceName

	msg, err := json.Marshal(readings)
	if err != nil {
		return false, fmt.Errorf("failed to transform Event to cloud format: %s", err)
	}

	return true, msg
}
